﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Telerik.Web.UI;
using System.Collections.Specialized;
using System.Data;
using SalePartial.Utility;
using XunPan.Web.Globals;
using System.Text.RegularExpressions;
using SalePartial.BLL;
using SalePartial.BLL.SAServiceRef;
using SalePartial.Model;
using System.Data.SqlClient;
using System.Text;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            int id = int.Parse(Request["id"]);
            DoRefreshVendorView();
            List<FamilyInfo> families = new List<FamilyInfo>();
            families = SABLL.GetFamiliesByVendorId(id, "");
            ViewState["data"] = SABLL.GetFamilyImageByFamilies(families);
            this.listView_Families.DataSource = (List<SAImageInfo>)ViewState["data"];
            this.listView_Families.DataBind();
        }
    }

    protected void SiteMapPath1_ItemDataBound(object sender, SiteMapNodeItemEventArgs e)
    {
        HyperLink hlk;
        if (e.Item.Controls[0] is HyperLink)
        {
            hlk = (HyperLink)e.Item.Controls[0];
            hlk.Attributes["target"] = e.Item.SiteMapNode["target"];
        }
    }

    private void AddNodeByCategoryInfo(RadTreeNodeCollection nodes, CategoryInfo cateInfo)
    {
        //add this node.
        RadTreeNode newNode = new RadTreeNode();
        newNode.Text = cateInfo.Name;
        newNode.Value = cateInfo.Id.ToString();
        nodes.Add(newNode);

        //add sub node.
        //get sub nodes.
        List<CategoryInfo> cateInfos = SABLL.GetSubCategories(cateInfo);

        if (cateInfos == null)
        {
            return;
        }

        foreach (CategoryInfo tempCateInfo in cateInfos)
        {
            string nae=tempCateInfo.Name;
            AddNodeByCategoryInfo(newNode.Nodes, tempCateInfo);
        }
    }



    private void DoRefreshVendorView()
    {
        
        int id = int.Parse(Request["id"]);
        try
        {
            //update categories.

            if (treeView_Vendor == null)
            {
                return;
            }
            //this.treeView_category.AllowDrop = true;
            this.treeView_Vendor.Nodes.Clear();


            List<CategoryInfo> cateInfos = SABLL.GetRootCategories();

                VendorInfo vendorInfo = SABLL.GetVendor(id);
                    


                RadTreeNode newNode = new RadTreeNode();
                newNode.Text = vendorInfo.Name;
                newNode.Value = vendorInfo.VendorId.ToString();
                treeView_Vendor.Nodes.Add(newNode);

                //now add categories.
                for (int j = 0; j < cateInfos.Count; j++)
                {
                    CategoryInfo curCateInfo = cateInfos[j];
                    bool bHasFamily = SABLL.IsCategoryContainsFamilyFromVendor(curCateInfo, vendorInfo.VendorId, true);
                    if (bHasFamily)
                    {
                        AddVendorCategoryNode(newNode, vendorInfo.VendorId, curCateInfo);
                    }
                }
           


            this.treeView_Vendor.ExpandAllNodes();

            //DoRefreshFamilyListView();
        }
        catch (System.Exception ex)
        {
            SABLL.ShowErrMsg(this, ex.Message);
        }
    }


    private void AddVendorCategoryNode(RadTreeNode parentNode, int vendorId, CategoryInfo categoryInfo)
    {
        if (parentNode == null)
        {
            return;
        }

        //add this node.
        RadTreeNode newNode = new RadTreeNode();
        newNode.Text = categoryInfo.Name;
        newNode.Value = categoryInfo.Id.ToString();
        //CategoryVendorHelpInfo cvInfo = new CategoryVendorHelpInfo();
        //cvInfo.cateID = categoryInfo.Id.ToString();
        //cvInfo.vendorID = vendorId;
        //newNode.Tag = cvInfo;
        newNode.Attributes.Add("cateID", categoryInfo.Id.ToString());
        newNode.Attributes.Add("vendorID", vendorId.ToString());

        parentNode.Nodes.Add(newNode);

        List<CategoryInfo> cateInfos = SABLL.GetSubCategories(categoryInfo);

        if (cateInfos == null)
        {
            return;
        }

        for (int i = 0; i < cateInfos.Count; i++)
        {
            CategoryInfo curCateInfo = cateInfos[i];

            bool bHasFamily = SABLL.IsCategoryContainsFamilyFromVendor(curCateInfo, vendorId, true);

            if (bHasFamily)
            {
                AddVendorCategoryNode(newNode, vendorId, curCateInfo);
            }
        }
    }

  

    protected void treeView_Vendor_AfterSelect(object sender, RadTreeNodeEventArgs e)
    {

        RadTreeNode node = this.treeView_Vendor.SelectedNode;
        IList<RadTreeNode> childNodes = node.GetAllNodes();
        childNodes.Add(node);
        string searchString = "";
        string CateIdByVendor = "";
        if (node != null)
        {
            List<FamilyInfo> families = new List<FamilyInfo>();
            int vendorId = 0;
            if (!IsGUID(node.Value))
            {

                int.TryParse(node.Value, out vendorId);

                families = SABLL.GetFamiliesByVendorId(vendorId, searchString);
            }
            else
            {

                string cateID = node.Attributes["cateID"];

                foreach (RadTreeNode item in childNodes)
                {
                    CateIdByVendor = CateIdByVendor + "CategoryID ='" + item.Value+ "'  or   ";
                }
       
                int.TryParse(node.Attributes["vendorID"], out vendorId);
                if (cateID != null && vendorId != 0)
                {
                    families = SABLL.GetFamiliesByCategoryVendorId(new Guid(cateID), vendorId, searchString, CateIdByVendor);
                }
            }

            ViewState["data"] = SABLL.GetFamilyImageByFamilies(families);
            bindGridData(true);
        }
    }

    protected bool IsGUID(string str)
    {
        Match m = Regex.Match(str, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", RegexOptions.IgnoreCase);
        if (m.Success)
        {
            //可以转换 
            //Guid guid = new Guid(str);
            return true;
        }
        else
        {
            //不可转换 
            return false;
        }
    }


    protected void listView_Families_NeedDataSource(object source, RadListViewNeedDataSourceEventArgs e)
    {
        bindGridData(false);
    }

    private void bindGridData(bool rebind)
    {
        if (ViewState["data"] != null)
        {
            this.listView_Families.DataSource = (List<SAImageInfo>)ViewState["data"];
            if (rebind)
            {
                this.listView_Families.DataBind();
            }
        }
    }

    protected void button_Search_Click(object sender, EventArgs e)
    {
        int id = int.Parse(Request["id"]);
        List<FamilyInfo> families = new List<FamilyInfo>();
        RadTreeNode node = new RadTreeNode();
        try
        {

            string searchString = this.textBox_Search.Text.ToString().ToUpper();
            if (String.IsNullOrEmpty(searchString))
            {
                families = SABLL.SearchFamiliesByVendor(searchString, id);
            }


            //ning_start
            
                    node = this.treeView_Vendor.SelectedNode;
                if (node != null)
                {
                IList<RadTreeNode> childNodes = node.GetAllNodes();
                childNodes.Add(node);
                string CateIdByVendor = "";
                foreach (RadTreeNode item in childNodes)
                {
                    CateIdByVendor = CateIdByVendor + "CategoryID ='" + item.Value + "'  or   ";
                }
                    int vendorId = 0;
                    string nos = node.Value;
                    if (!IsGUID(node.Value))
                    {
                        int.TryParse(node.Value, out vendorId);
                        families = SABLL.GetFamiliesByVendorId(vendorId, searchString);
                    }
                    else
                    {
                        string cateID = node.Attributes["cateID"];

                        int.TryParse(node.Attributes["vendorID"], out vendorId);
                        if (cateID != null && vendorId != 0)
                        {
                            families = SABLL.GetFamiliesByCategoryVendorId(new Guid(cateID), vendorId, searchString, CateIdByVendor);
                         }

                    }
            }
            else 
            {
                families = SABLL.SearchFamiliesByVendor(searchString, id);
            }


                ViewState["data"] = SABLL.GetFamilyImageByFamilies(families);
                bindGridData(true);
        }
        catch (System.Exception ex)
        {
            SABLL.ShowInfoMsg(this, ex.Message);


        }
        finally
        {
        }
    }


  

    protected Unit ImageWidth
    {
        get
        {
            object state = ViewState["ImageWidth"] ?? Unit.Pixel(100);
            return (Unit)state;
        }
        private set { ViewState["ImageWidth"] = value; }
    }

    protected Unit ImageHeight
    {
        get
        {
            object state = ViewState["ImageHeight"] ?? Unit.Pixel(100);
            return (Unit)state;
        }
        private set { ViewState["ImageHeight"] = value; }
    }

    protected string CreateWindowScript(Object info)
    {
        //string kk = ((SAImageInfo)info).VendorId.ToString();
        return string.Format("var win = window.open('Default4.aspx?familyId={0}&id={1}','_self');", ((SAImageInfo)info).Id, ((SAImageInfo)info).VendorId);
        
    }

    public static string TruncateWithEllipsis(string text, int length)
    {
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        byte[] s = ascii.GetBytes(text);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            if (tempLen >= (length - 1) * 2)
            {
                text = text.Substring(0, i) + "...";
                break;
            }
        }

        //for(int i=1;i<text.Length;i++)
        //{
        //    if (text.Substring(0, i).ToCharArray().Length >= (length-1) * 2)
        //    {
        //        text = text.Substring(0, i) + "...";
        //        break;
        //    }
        //}


        return text;

    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        var textBox = (TextBox)sender;
        var keyValue = (int)((RadListViewDataItem)textBox.NamingContainer).GetDataKeyValue("Id");
        //  DataProvider.Update(keyValue, textBox.Text.Trim());
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("ComponentsIntro.aspx");
    }

    protected void Help_Click(object sender, EventArgs e)
    {
        Response.Redirect("ComponentsIntro.aspx");
    }

}